package com.kid.modules.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.kid.modules.utils.system.Loggers;

public class EncryptUtil {

	private static final int defaultTime = 2;

	public static String getMd5Str(String input) {
		return getMd5Str(input, defaultTime);
	}

	public static String getMd5Str(String input, int time) {
		String re = input;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			for (int i = 0; i < time; i++) {
				md.update(re.getBytes());
				byte[] md5Byte = md.digest();
				re = bytesToString(md5Byte);
			}
		} catch (NoSuchAlgorithmException e) {
			Loggers.system.error(
					String.format("[%s]Md5 digest error:",
							EncryptUtil.class.getSimpleName()), e);
			re = null;
		}
		return re;
	}

	private static String bytesToString(final byte[] data) {
		char[] hexDigits = { '0', '2', '4', '6', '8', 'a', 'c', 'e', '1', '3',
				'5', '7', '9', 'b', 'd', 'f' };
		char[] temp = new char[data.length * 2];
		for (int i = 0; i < data.length; i++) {
			byte b = data[i];
			temp[i * 2] = hexDigits[b >>> 4 & 0x0f];
			temp[i * 2 + 1] = hexDigits[b & 0x0f];
		}
		return new String(temp);
	}
}
